<template>
  <div class="plan-content" @click="changeType(-1)">
    <div class="nx-content">
      <div class="flex-cen">
        <div class="left-title flex"></div>
        <el-form ref="searchForm" :inline="true" :model="searchForm" class="demo-form-inline">
          <el-form-item label="">
            <el-cascader v-model="searchForm.companyId" placeholder="请选择公司名称" :options="companyArray" :props="{
              checkStrictly: true,
              value: 'id',
              label: 'name',
              children: 'childList',
            }" @change="changeTreeItem" clearable></el-cascader>
          </el-form-item>
          <el-form-item label="">
            <el-select v-model="searchForm.baseId" placeholder="请选择基地名称" clearable>
              <el-option v-for="item in baseArray" :key="item.id" :label="item.name" :value="item.id"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="">
            <el-input maxlength="50" placeholder="请输入控制箱编号" v-model="searchForm.boxCode" clearable></el-input>
          </el-form-item>
          <el-form-item label="">
            <el-input maxlength="50" placeholder="请输入排水分组" v-model="searchForm.dischargeWaterGroupId"
              clearable></el-input>
          </el-form-item>
          <el-form-item label="">
            <el-input maxlength="50" placeholder="请输入鱼池编号" v-model="searchForm.fishpondCode" clearable></el-input>
          </el-form-item>
          <el-form-item>
            <div v-allow="'050101'" class="search" @click="listStorageCycle">
              <img class="glass" src="../../../assets/schedule/glass.png" alt="" />
              查询
            </div>
          </el-form-item>
        </el-form>
      </div>
      <div class="flex-cen" style="margin-top:50px;">
        <div class="labelitem" @click.stop="changeType(0)">
          <div class="cricle green" v-bind:class="['cricle', 'green', typeVal === 0 ? 'redborder' : '']"></div>
          <span>投料</span>
        </div>
        <div class="labelitem" @click.stop="changeType(1)">
          <div v-bind:class="['cricle', 'grey', typeVal == 1 ? 'redborder' : '']"></div>
          <span>排污</span>
        </div>
        <div class="labelitem" @click.stop="changeType(2)">
          <div v-bind:class="['cricle', 'blue', typeVal == 2 ? 'redborder' : '']"></div>
          <span>换水</span>
        </div>
        <div class="labelitem" @click.stop="changeType(3)">
          <div v-bind:class="['cricle', 'purple', typeVal == 3 ? 'redborder' : '']"></div>
          <span>增氧</span>
        </div>
      </div>
      <div class="titleycboxout">
        <div class="titleycbox">
          <div class="yleft">
            <div class="circle"></div>
            鱼池编号
          </div>
          <div class="yleft">
            <div class="circle"></div>
            排水分组
          </div>
        </div>
      </div>
      <div class="time" onselectstart="return false">
        <div v-loading="btnLoading">
          <div class="title-box">
            <!-- <span>类型</span>
                <el-select
                    v-model="typeVal"
                    @change="onSelect"
                    placeholder="请选择存储计划周期类型"
                    size="small"
                    class="w200 title"
                >
                    <el-option
                        v-for="dict in options"
                        :key="dict.value"
                        :label="dict.label"
                        :value="parseInt(dict.value)"
                    />
                </el-select> -->
          </div>

          <div class="df">
            <div class="week-box">
              <div class="week" v-for="week of weekList" :key="week.code" @mouseenter="copyMouseenter(week.title)">
                <!-- 周几 -->
                <span>{{ week.title }}</span>
              </div>
            </div>
            <div class="dfcontent">
              <!-- 整个时间功能 -->
              <div class="cycle-box" v-for="week of weekList" :key="week.code" @mouseenter="copyMouseenter(week.title)">
                <div class="slide-list">
                  <!-- 时间刻度 -->
                  <div class="slide-ruler">
                    <div class="scale" v-for="time of timeList" :key="time">
                      {{ time }}
                    </div>
                  </div>

                  <!-- 时间功能数组中控制周几是否能创建数据disabled -->
                  <div :style="
                    week.disabled
                      ? 'background:#C0C8D9;cursor:not-allowed;'
                      : ''
                  " class="slide-box" @click.stop="defaultAdd($event, week.code, week)">
                    <!-- 初始化的domObj，宽度不等于0并且week.code == code才显示 -->
                    <!-- <div
                                    v-show="
                                        domObj.width != 0 && week.code == code
                                    "
                                    class="item"
                                    :style="{'width':domObj.width+'px','left':domObj.left+'px','backgroundImage': 'url(' + domObj.bg + ')'}"
                                ></div> -->

                    <!-- 创建的时间块数组domArr -->
                    <div v-for="(item, key) of week.domArr" :key="key" class="item" :style="{
                      width: item.width + 'px',
                      left: item.left + 'px',
                      backgroundImage: 'url(' + item.bg + ')',
                    }" @mousedown.stop="
  itemMousedown($event, week.code, key, item, week.domArr)
" @click.stop="timeBlock(week.code, key, item)">
                      <img style="width:48px;height:20px" v-if="item.value == 0 || item.value == 3"
                        src="../../../assets/yu.png" />
                      <img style="width:20px;height:20px" v-if="item.value == 2" src="../../../assets/shui.png" />
                      <img style="width:20px;height:20px" v-if="item.value == 1" src="../../../assets/wu.png" />
                      <i v-show="item.changeTimeShow && iShow === key" class="i-left-class i-class" @mousedown.stop="
                        checkI('left', $event, code, key, item, week.domArr)
                      "></i>
                      <i v-show="item.changeTimeShow && iShow === key" class="i-right-class i-class" @mousedown.stop="
                        checkI('right', $event, code, key, item, week.domArr)
                      "></i>
                      <!-- hover时间展示 -->
                      <div :style="{
                        left: (item.width < 50 ? -30 : -15) + 'px',
                        position: 'absolute',
                        top: '-35px',
                        width: '100%',
                        height: '100%',
                      }">
                        <div role="tooltip" id="el-tooltip-1745" aria-hidden="false" class="el-tooltip__popper">
                          <div data-v-7881806f="" style="text-align: center;">
                            {{ item.startH }}:{{ item.startM }}
                          </div>
                          <div x-arrow="" class="popper__arrow" style="left: 12.5px;top:18px"></div>
                        </div>
                        <!-- <el-tooltip placement="top" :value="visible" :manual="visible">
                                            <div
                                                style="text-align: center"
                                                slot="content"
                                            >
                                                {{ item.startH }}:{{
                                                    item.startM
                                                }}
                                            </div>
                                            <div class="timeHover"></div>
                                        </el-tooltip> -->
                      </div>
                      <div :style="{
                        left: (item.width < 50 ? 11 : item.width - 26) + 'px',
                        position: 'absolute',
                        top: '-35px',
                        width: '100%',
                        height: '100%',
                      }">
                        <div role="tooltip" id="el-tooltip-1745" aria-hidden="false"
                          class="tps el-tooltip__popper is-dark">
                          <div data-v-7881806f="" style="text-align: center;">
                            {{ item.endH }}:{{ item.endM }}
                          </div>
                          <div x-arrow="" class="popper__arrow" style="left: 12.5px;top:18px"></div>
                        </div>
                        <!-- <el-tooltip popper-class="tps" placement="top" :value="visible" :manual="visible">
                                            <div
                                                style="text-align: center"
                                                slot="content"
                                            >
                                                {{ item.endH }}:{{
                                                    item.endM
                                                }}
                                            </div>
                                            <div class="timeHover"></div>
                                        </el-tooltip> -->
                      </div>

                      <!-- 点击时间调整 -->
                      <el-popover placement="top" trigger="manual" v-model="item.changeTimeShow" @show="showFun(item)"
                        @hide="hideFun(item)">
                        <div style="text-align: center">
                          <div>
                            <el-select v-model="sonVal" placeholder="请选择存储计划周期类型" size="mini" class="w200">
                              <el-option v-for="dict in options" :key="dict.value" :label="dict.label"
                                :value="dict.value" />
                            </el-select>
                          </div>
                          <div style="margin: 15px 0">
                            <input size="mini" class="w40" v-model="item.startH" maxlength="2"
                              @input="hhInput('startH', week.code, key, item)" />
                            <span style="padding: 0 5px">:</span>
                            <input size="mini" class="w40" v-model="item.startM" maxlength="2"
                              @input="mmInput('startM', week.code, key, item)" />
                            <span style="padding: 0 5px">-</span>
                            <input size="mini" class="w40" v-model="item.endH" maxlength="2"
                              @input="hhInput('endH', week.code, key, item)" />
                            <span style="padding: 0 5px">:</span>
                            <input size="mini" class="w40" v-model="item.endM" maxlength="2"
                              @input="mmInput('endM', week.code, key, item)" />
                          </div>
                          <div>
                            <el-button-group>
                              <el-button size="mini" type="primary" @click="
                                btns(
                                  'delete',
                                  week.code,
                                  key,
                                  item,
                                  week.domArr
                                )
                              ">删除</el-button>
                              <el-button size="mini" type="primary"
                                @click="btns('cancel', week.code, key, item)">取消</el-button>
                              <el-button size="mini" type="primary"
                                @click="btns('ok', week.code, key, item)">确定</el-button>
                            </el-button-group>
                          </div>
                        </div>
                        <div slot="reference" class="timeHover"></div>
                      </el-popover>
                    </div>
                  </div>
                </div>
                <span></span>
              </div>
            </div>
            <div class="week-box">
              <div class="week" style="margin-left:30px" v-for="week of weekList" :key="week.code"
                @mouseenter="copyMouseenter(week.title)">
                <span>{{ week.dischargeWaterGroupId }}</span>
              </div>
            </div>
          </div>
        </div>

        <div class="rbtn">
          <div v-allow="'050103'" class="removebtn" @click="deleteAllFun" v-if="showsave">
            <img src="../../../assets/remove.png" />
            删除全部
          </div>
          <div v-allow="'050102'" class="btnsave" @click="submit" v-if="showsave">
            保存
          </div>
          <div class="btnsave" @click="submitRW" v-if="showsave">任务下发</div>
          <div class="btnsave">操作帮助</div>
          <!-- <el-button type="primary" :loading="btnLoading" @click="submit">确定</el-button> -->
        </div>
      </div>
    </div>
  </div>
</template>
<script>
import {
  getObjBoxTaskList,
  getSysCompanyBases,
  saveConfigFishpondTasks,
  sendBaseBoxCmd,
} from '@/api/system'
import { getCompanyInfoTree } from '@/api/company'
export default {
  components: {},
  // 表格数据
  data() {
    return {
      visible: true,
      searchForm: {
        pageNum: 1,
        pageSize: 10,
        userType: '',
        companyId: '',
        baseId: '',
        boxCode: '',
        dischargeWaterGroupId: '',
        fishpondCode: '',
      },
      companyArray: [],
      showsave: true,
      baseArray: [],
      btnLoading: false,
      // 删除的id，只有要传[]时才调用
      deleteId: [],

      // 下拉框所有数据
      options: [
        { label: '投料', value: 0 },
        { label: '换水', value: 1 },
        { label: '排水', value: 2 },
        { label: '增氧', value: 3 },
      ],
      // 下拉框选中的数据
      typeVal: -1,
      // 删除所有数据
      deleteAll: false,
      // 核心数据
      // 刻度
      timeList: [0, 2, 4, 6, 8, 10, 12, 14, 16, 18, 20, 22, 24],
      // 所有数据
      weekList: [],
      // 声明的DOM对象
      domObj: {},
      // 控制能做几个时间块
      allNum: 99,
      // 所有数据的code值
      code: 0,
      // 所有数据内domArr的下标值
      key: null,
      timeVal: null,
      // 存根数据
      stubData: {},
      // 是否是选中的时间子块
      loop: 0,
      // 子块的hover是否显示
      blockShow: true,
      // 左右i的显示
      iShow: null,
      // 每个子块的下拉框
      sonVal: null,
      // 小弹框显示前的存根数据，防止修改了时间不点击按钮组直接点空取消弹框而导致时间bug问题
      popoverStubData: [],

      // 复制相关
      // 控制是否显示复制
      copyShow: false,
      codeHover: null,
      checkAll: false,
      isIndeterminate: false,
      copyValue: null,
    }
  },
  created() {
    this.init()
    // console.log(1);
  },
  // 初始化加载
  mounted() {
    //   this.searchForm.companyId = Number(window.localStorage.getItem("companyId"));
    this.userType = Number(window.localStorage.getItem('userType'))
    this.searchForm.userType = this.userType
    this.getCompanyInfoTree()
  },

  // 自定义方法
  methods: {
    changeType(type) {
      this.typeVal = type
      this.onSelect(type)
    },
    onSubmit() {
      // this.getList();
    },
    init() {
      this.domObj = {
        width: 0, //宽度
        left: 0, //左偏移量
        bg: require('../../../assets/pai1.png'), //背景色（与背景值关联，对应着下拉框的值
        value: 0, //背景值（与背景色关联，对应着下拉框的值
        startH: 0, //开始时间（时
        startM: 0, //开始时间（分
        endH: 0, //结束时间（时
        endM: 0, //结束时间（分
        changeTimeShow: false, //控制时间显示与时间调整
      }
    },
    // 下拉框选择
    onSelect(code) {
      this.domObj = {
        width: 0, //宽度
        left: 0, //左偏移量
        value: code, //背景值（与背景色关联，对应着下拉框的值
        startH: 0, //开始时间（时
        startM: 0, //开始时间（分
        endH: 0, //结束时间（时
        endM: 0, //结束时间（分
        changeTimeShow: false,
      }
      if (code == 0) {
        this.domObj.bg = require('../../../assets/pai1.png')
      } else if (code == 1) {
        this.domObj.bg = require('../../../assets/pai2.png')
      } else if (code == 2) {
        this.domObj.bg = require('../../../assets/pai3.png')
      } else if (code == 3) {
        this.domObj.bg = require('../../../assets/pai4.png')
      }
    },
    // 删除所有数据
    deleteAllFun() {
      this.deleteAll = false
      let weekList = this.weekList
      weekList.forEach((item) => {
        item.domArr = []
      })
      this.weekList = weekList
      // this.init();
    },
    // 进入周几事件后的拷贝功能
    copyMouseenter(title) {
      this.codeHover = title
    },
    // 点击投料，排污，换水，增氧后可以在横条中生成鱼 添加
    defaultAdd(e, code, item) {
      if (!this.ismove) {
        this.code = code
        // let op = e.target
        // // 算出鼠标相对元素的位置
        // let disX = e.clientX
        // console.log(e.clientX, op.offsetLeft, "相对位置是他left的值", disX);
        // left
        // this.domObj=JSON.parse(JSON.stringify(this.domObj))
        this.domObj.left = e.layerX
        // 开始时间
        this.domObj.startH = this.conversionhs('H', this.domObj.left * 2)
        this.domObj.startM = this.conversionhs('M', this.domObj.left * 2)
        // 改变鱼的长短
        if (this.typeVal == 1 || this.typeVal == 2) {
          this.domObj.width = 50
        } else if (this.typeVal == 3) {
          this.domObj.width = 50
        } else if (this.typeVal == 0) {
          this.domObj.width = 50
        }
        // 拖动的宽不能大于刻度，否则就等于刻度-偏移的left = 最终宽
        if (this.domObj.width + this.domObj.left > 7200) {
          this.domObj.width = 7200 - this.domObj.left
        }
        // 结束时间
        this.domObj.endH = this.conversionhs(
          'H',
          this.domObj.left * 2 + this.domObj.width * 2
        )
        this.domObj.endM = this.conversionhs(
          'M',
          this.domObj.left * 2 + this.domObj.width * 2
        )
        if (this.typeVal != -1) {
          // console.log(item.domArr)
          this.domObj.dischargeWaterGroupId = this.weekList[
            code
          ].dischargeWaterGroupId
          // console.log(JSON.parse(JSON.stringify(this.domObj)));

          let _domObj = JSON.parse(JSON.stringify(this.domObj)),
            dateKey = new Date().getTime()
          _domObj.dateKey = dateKey
          item.domArr.push(_domObj)

          // setTimeout(() => {
          //     item.domArr = []
          // }, 3000);
          let dischargeWaterGroupId = this.weekList[code].dischargeWaterGroupId

          let value = this.domObj.value
          if (
            dischargeWaterGroupId &&
            (value == 0 || value == 1 || value == 2 || value == 3)
          ) {
            this.weekList.forEach((citem, index) => {
              // console.log('this.weekList', this.weekList);
              citem.domArr.forEach((jitem, jindex) => {
                if (
                  code != index &&
                  jitem.dischargeWaterGroupId == dischargeWaterGroupId &&
                  jitem.value == this.domObj.value
                ) {
                  citem.domArr.splice(jindex, 1)
                }
              })
            })
            //  便利鱼可以一次添加四个
            // 这里添加鱼的数组有问题 ！！！！！！
            let psarr = []
            this.weekList.forEach((citem, index) => {
              // console.log('citem', citem)

              citem.domArr.forEach((jitem, jindex) => {
                // console.log(jitem)
                if (
                  code == index &&
                  jitem.dischargeWaterGroupId == dischargeWaterGroupId &&
                  jitem.value == this.domObj.value
                ) {
                  // 可以用来限制次数
                  psarr.push(jitem)
                }
              })
            })
            // console.log('psarr', psarr)
            this.weekList.forEach((citem, index) => {
              if (
                code != index &&
                citem.dischargeWaterGroupId == dischargeWaterGroupId
              ) {
                psarr.forEach((ps) => {
                    let index = citem.domArr.findIndex(el2 => ps.dateKey === el2.dateKey)
                    if(index==-1){
                        citem.domArr.push(JSON.parse(JSON.stringify(ps)))
                    }
                    // citem.domArr.push(JSON.parse(JSON.stringify(ps)))
                })
              }
            })
            console.log(this.weekList);
          }
        }
        document.onmousemove = null
        document.onmouseup = null
      }
    },
    // 父节点的按下事件
    // fatherMousedown(e, code, item) {
    //   // console.log(1);
    //   // 控制是否还能创建
    //   if (item.domArr.length >= this.allNum || item.disabled) {
    //     return false
    //   }
    //   this.code = code
    //   let op = e.target
    //   // 算出鼠标相对元素的位置
    //   let disX = e.clientX
    //   // console.log(e.clientX, op.offsetLeft, "相对位置是他left的值", disX);
    //   // left
    //   this.domObj.left = e.layerX
    //   // 开始时间
    //   this.domObj.startH = this.conversionhs('H', this.domObj.left * 2)
    //   this.domObj.startM = this.conversionhs('M', this.domObj.left * 2)
    //   let that = this
    //   //鼠标移动事件
    //   document.onmousemove = (e) => {
    //     // console.log(e);
    //     that.ismove = true
    //     //用鼠标的位置减去鼠标相对元素的位置，得到元素的位置
    //     this.domObj.width = e.clientX - disX
    //     // 拖动的宽不能大于刻度，否则就等于 刻度-偏移的left = 最终宽
    //     if (this.domObj.width + this.domObj.left > 7200) {
    //       this.domObj.width = 7200 - this.domObj.left
    //     }
    //     // 结束时间
    //     this.domObj.endH = this.conversionhs(
    //       'H',
    //       this.domObj.left * 2 + this.domObj.width * 2
    //     )
    //     this.domObj.endM = this.conversionhs(
    //       'M',
    //       this.domObj.left * 2 + this.domObj.width * 2
    //     )
    //   }
    //   // 鼠标抬起事件
    //   document.onmouseup = (e) => {
    //     setTimeout(function () {
    //       that.ismove = false
    //     }, 300)
    //     if (this.domObj.width > 10 && this.typeVal != -1) {
    //       this.domObj.dischargeWaterGroupId = this.weekList[
    //         code
    //       ].dischargeWaterGroupId
    //       // item.domArr.push(JSON.parse(JSON.stringify(this.domObj)))
    //       // console.info('新增'+this.domObj.width)

    //       let dischargeWaterGroupId = this.weekList[code].dischargeWaterGroupId
    //       let value = this.domObj.value
    //       if (
    //         dischargeWaterGroupId &&
    //         (value == 1 || (value == 2) | (value == 0) | (value == 3))
    //       ) {
    //         return
    //       }
    //     }
    //     this.onSelect(this.typeVal)
    //     document.onmousemove = null
    //     document.onmouseup = null
    //   }
    // },
    // 子块节点的长按
    itemMousedown(e, code, key, item, arr) {
      this.loop = setTimeout(() => {
        this.loop = 0
        let disX = e.clientX
        let blockLeft = item.left //左边偏移量left
        let blockWidth = item.width //子滑块的宽
        // 控制子块长按时的hover显示
        this.blockShow = false
        item.changeTimeShow = false
        // console.log('是否显示了按钮组',item.changeTimeShow)
        let arrCopy = JSON.parse(JSON.stringify(arr))
        // 对需要移动的子块的所在数组重新按照left大小排序
        function sortLeft(a, b) {
          return a.left - b.left
        }
        arrCopy.sort(sortLeft)
        // 处理左右滑动的范围
        let leftL = 0 // 往左滑动的范围
        let leftR = 7200 // 往右滑动的范围
        let mark = 0
        for (let i = 0; i < arrCopy.length; i++) {
          if (arrCopy[i].left === item.left) {
            mark = i
            break
          }
        }
        if (arrCopy.length === 1) {
          leftL = 0 // 往左滑动的范围
          leftR = 7200 // 往右滑动的范围
        } else {
          if (mark === 0) {
            leftL = 0 // 往左滑动的范围
            leftR = arrCopy[mark + 1].left // 往右滑动的范围
          } else if (mark === arrCopy.length - 1) {
            leftL = arrCopy[mark - 1].left + arrCopy[mark - 1].width
            leftR = 7200
          } else if (mark !== 0 && mark < arrCopy.length - 1) {
            leftL = arrCopy[mark - 1].left + arrCopy[mark - 1].width
            leftR = arrCopy[mark + 1].left
          }
        }
        // console.log('arrCopy==',arrCopy,'==mark=',mark,'=leftL=',leftL,'=leftR=',leftR)
        // 子块鼠标移动事件
        document.onmousemove = (e) => {
          console.log(item.left, leftL)
          console.log(
            e,
            '子块滑动事件',
            e.clientX,
            '--==--',
            e.clientX - disX,
            '---left=',
            blockLeft + (e.clientX - disX)
          )
          if (blockLeft + (e.clientX - disX) <= leftL) {
            item.left = leftL
          } else if (item.width + (blockLeft + (e.clientX - disX)) <= leftR) {
            // console.log('总长==',item.width + blockLeft + (e.clientX - disX))
            item.left = blockLeft + (e.clientX - disX)
          }
          // 开始时间
          item.startH = this.conversionhs('H', item.left * 2)
          item.startM = this.conversionhs('M', item.left * 2)
          // 结束时间
          item.endH = this.conversionhs('H', item.left * 2 + item.width * 2)
          item.endM = this.conversionhs('M', item.left * 2 + item.width * 2)
        }
        // 子块鼠标抬起事件
        document.onmouseup = (e) => {
          this.blockShow = true
          this.iShow = null
          document.onmousemove = null
          document.onmouseup = null

          let dischargeWaterGroupId = this.weekList[code].domArr[key]
            .dischargeWaterGroupId
          let value = item.value
          // 一条鱼动四条鱼跟着一起动
          if (
            dischargeWaterGroupId &&
            (value == 1 || value == 2 || (value == 0) | (value == 3))
          ) {
            this.weekList.forEach((item, index) => {
              item.domArr.forEach((jitem, jindex) => {
                if (
                  code != index &&
                  jitem.dischargeWaterGroupId == dischargeWaterGroupId &&
                  jitem.value == value
                ) {
                  item.domArr.splice(jindex, 1)
                }
              })
            })
            let psarr = []
            this.weekList.forEach((item, index) => {
              item.domArr.forEach((jitem, jindex) => {
                if (
                  code == index &&
                  jitem.dischargeWaterGroupId == dischargeWaterGroupId &&
                  jitem.value == value
                ) {
                  psarr.push(jitem)
                }
              })
            })
            this.weekList.forEach((item, index) => {
              if (
                code != index &&
                item.dischargeWaterGroupId == dischargeWaterGroupId
              ) {
                psarr.forEach((ps) => {
                    let index = item.domArr.findIndex(el2 => ps.dateKey === el2.dateKey)
                    if(index==-1){
                        item.domArr.push(JSON.parse(JSON.stringify(ps)))
                    }
                //   item.domArr.push(JSON.parse(JSON.stringify(ps)))
                })
              }
            })
          }
          console.info(this.weekList)
          //存疑
          // let weekList = this.weekList
          // this.weekList = []
          // this.weekList = weekList
        }
      }, 200)

      return false
    },
    // 子块节点的单击
    timeBlock(code, key, item) {
      clearTimeout(this.loop)
      if (this.loop !== 0) {
        this.iShow = key
        this.sonVal = item.value
        // console.log('单击=',code, key, JSON.stringify(item) );
        this.stubData = JSON.parse(JSON.stringify(item))
        // 找到对应的节点，根据条件把对应节点打开或者关闭，但是其它节点要全部关闭
        this.weekList.map((v, i) => {
          v.domArr.map((val, j) => {
            if (i == code && j == key) {
              item.changeTimeShow = !item.changeTimeShow
            } else {
              this.weekList[i].domArr[j].changeTimeShow = false
            }
          })
        })
      }
      return false
    },
    // 选中的左右小方块
    checkI(type, e, code, key, item, arr) {
      this.loop = setTimeout(() => {
        this.loop = 0
        let disX = e.clientX
        let blockLeft = item.left //左边偏移量left
        let blockWidth = item.width //子滑块的宽
        item.changeTimeShow = false
        item.value = this.stubData.value
        // console.log(item,'--->>>>>',this.stubData)
        // console.log('type==>>点击的那个',type, e, key, item, arr)
        let arrCopy = JSON.parse(JSON.stringify(arr))
        // 对需要移动的子块的所在数组重新按照left大小排序
        function sortLeft(a, b) {
          return a.left - b.left
        }
        arrCopy.sort(sortLeft)
        // 处理左右滑动的范围
        let leftL = 0 // 往左滑动的范围
        let leftR = 7200 // 往右滑动的范围
        let mark = 0
        for (let i = 0; i < arrCopy.length; i++) {
          if (arrCopy[i].left === item.left) {
            mark = i
            break
          }
        }
        if (arrCopy.length === 1) {
          leftL = 0 // 往左滑动的范围
          leftR = 7200 // 往右滑动的范围
        } else {
          if (mark === 0) {
            leftL = 0 // 往左滑动的范围
            leftR = arrCopy[mark + 1].left // 往右滑动的范围
          } else if (mark === arrCopy.length - 1) {
            leftL = arrCopy[mark - 1].left + arrCopy[mark - 1].width
            leftR = 7200
          } else if (mark !== 0 && mark < arrCopy.length - 1) {
            leftL = arrCopy[mark - 1].left + arrCopy[mark - 1].width
            leftR = arrCopy[mark + 1].left
          }
        }
        // console.log('arrCopy==',arrCopy,'==mark=',mark,'=leftL=',leftL,'=leftR=',leftR)
        // 子块鼠标移动事件
        document.onmousemove = (e) => {

          console.log(
            blockWidth,
            '子块滑动事件',
            e.clientX,
            '--==-运算的-',
            e.clientX - disX,
            '---left=',
            blockLeft + (e.clientX - disX)
          )
          if (type === 'left') {
            if (blockLeft + (e.clientX - disX) < leftL) {
              item.left = leftL
            } else {
              if (blockWidth - (e.clientX - disX) >= 0) {
                item.left = blockLeft + (e.clientX - disX)
                item.width = blockWidth - (e.clientX - disX)
              }
            }
          } else if (type === 'right') {
            if (blockWidth + (blockLeft + (e.clientX - disX)) <= leftR) {
              item.width = blockWidth + (e.clientX - disX)
            }
          }
          // 开始时间
          item.startH = this.conversionhs('H', item.left * 2)
          item.startM = this.conversionhs('M', item.left * 2)
          // 结束时间
          item.endH = this.conversionhs('H', item.left * 2 + item.width * 2)
          item.endM = this.conversionhs('M', item.left * 2 + item.width * 2)
        }
        // 左右小方块的鼠标抬起事件
        document.onmouseup = (e) => {
          this.iShow = null
          console.log(1)
          if (item.width <= 0) {
            this.weekList[code].domArr.splice(key, 1)
          }
          document.onmousemove = null
          document.onmouseup = null
        }
      }, 200)
      let dischargeWaterGroupId = this.weekList[code].domArr[key]
        .dischargeWaterGroupId
      let value = item.value
      if (
        dischargeWaterGroupId &&
        (value == 1 || value == 2 || (value == 3) | (value == 0))
      ) {
        this.weekList.forEach((item, index) => {
          item.domArr.forEach((jitem, jindex) => {
            if (
              code != index &&
              jitem.dischargeWaterGroupId == dischargeWaterGroupId &&
              jitem.value == value
            ) {
              item.domArr.splice(jindex, 1)
            }
          })
        })
        let psarr = []
        this.weekList.forEach((item, index) => {
          item.domArr.forEach((jitem, jindex) => {
            if (
              code == index &&
              jitem.dischargeWaterGroupId == dischargeWaterGroupId &&
              jitem.value == value
            ) {
              psarr.push(jitem)
            }
          })
        })
        this.weekList.forEach((item, index) => {
          if (
            code != index &&
            item.dischargeWaterGroupId == dischargeWaterGroupId
          ) {
            psarr.forEach((ps) => {
                let index = item.domArr.findIndex(el2 => ps.dateKey === el2.dateKey)
                if(index==-1){
                    item.domArr.push(JSON.parse(JSON.stringify(ps)))
                }
            //   item.domArr.push(JSON.parse(JSON.stringify(ps)))
            })
          }
        })
      }
      return false
    },
    // px 换算 时,分
    conversionhs(type, timeNum) {
      if (type == 'H') {
        return parseInt(timeNum / 600) < 10
          ? '0' + parseInt(timeNum / 600)
          : parseInt(timeNum / 600)
      } else if (type == 'M') {
        timeNum = timeNum - parseInt(timeNum / 600) * 600
        return parseInt((timeNum * 60) / 600) < 10
          ? '0' + parseInt((timeNum * 60) / 600)
          : parseInt((timeNum * 60) / 600)
      }
    },
    // 时，分 换算成 px
    conversionpx(type, pxNum) {
      if (type == 'left') {
        return (parseInt(pxNum.startH) * 600 + parseInt(pxNum.startM) * 10) / 2
      } else if (type == 'width') {
        return (
          (parseInt(pxNum.endH) * 600 +
            parseInt(pxNum.endM) * 10 -
            (parseInt(pxNum.startH) * 600 + parseInt(pxNum.startM) * 10)) /
          2
        )
      }
    },
    // 点击时间调整-按钮组
    btns(type, code, key, item, arr) {
      console.log('delete', type, code, key, item)
      console.log(this.weekList)
      // console.log('==1');
      let dischargeWaterGroupId = this.weekList[code].dischargeWaterGroupId
      if (type == 'delete') {
        // console.log(this.weekList[code]);
        // console.log('key', key);
        // console.log(this.weekList[code].domArr);
        console.log(this.weekList)
        this.weekList.forEach((el,elindex) => {
            let index = el.domArr.findIndex(el2 => item.dateKey === el2.dateKey)
            el.domArr.splice(index, 1)
        })

        // this.weekList[code].domArr.splice(key, 1)
      } else if (type == 'cancel') {
        this.weekList[code].domArr[key] = this.stubData
        item.changeTimeShow = false
        this.iShow = null
      } else if (type == 'ok') {
        // console.log('点击ok要执行的操作',item,item.startM)
        item.startH = this.timeVerification(item.startH)
        item.startM = this.timeVerification(item.startM)
        item.endH = this.timeVerification(item.endH)
        item.endM = this.timeVerification(item.endM)
        this.operate(code, item)
      }
      return
    },
    // 颜色调整
    adjustment(val) {
      if (val == 0) {
        return require('../../../assets/pai1.png')
      } else if (val == 1) {
        return require('../../../assets/pai2.png')
      } else if (val == 2) {
        return require('../../../assets/pai3.png')
      } else if (val == 3) {
        return require('../../../assets/pai4.png')
      }
    },
    // 按钮组-确定-验证逻辑
    operate(code, item) {
      // 1-时间验证
      if (
        parseInt(item.startH) > parseInt(item.endH) ||
        (parseInt(item.startH) == parseInt(item.endH) &&
          parseInt(item.startM) >= parseInt(item.endM))
      ) {
        this.$message({
          type: 'warning',
          message: '开始时间必须早于结束时间',
        })
      }
      // 2-区域变更
      let domArr = this.weekList[code].domArr
      // console.log('查找对应星期的所有时间块数据==',domArr,item)
      let arrCopy = JSON.parse(JSON.stringify(domArr))
      // 对需要移动的子块的所在数组重新按照left大小排序
      function sortLeft(a, b) {
        return a.left - b.left
      }
      arrCopy.sort(sortLeft)
      let mark = 0
      for (let i = 0; i < arrCopy.length; i++) {
        if (arrCopy[i].left === item.left) {
          mark = i
          break
        }
      }
      if (arrCopy.length !== 1) {
        if (mark === 0) {
          if (
            `${arrCopy[mark].endH}:${arrCopy[mark].endM}` >
            `${arrCopy[mark + 1].startH}:${arrCopy[mark + 1].startM}`
          ) {
            this.$message({
              type: 'warning',
              message: '时间段存在重复，请检查后重新设置',
            })
            return false
          }
        } else if (mark === arrCopy.length - 1) {
          if (
            `${arrCopy[mark].startH}:${arrCopy[mark].startM}` <
            `${arrCopy[mark - 1].endH}:${arrCopy[mark - 1].endM}`
          ) {
            this.$message({
              type: 'warning',
              message: '时间段存在重复，请检查后重新设置',
            })
            return false
          }
        } else if (mark !== 0 && mark < arrCopy.length - 1) {
          if (
            `${arrCopy[mark].startH}:${arrCopy[mark].startM}` <
            `${arrCopy[mark - 1].endH}:${arrCopy[mark - 1].endM}` ||
            `${arrCopy[mark].endH}:${arrCopy[mark].endM}` >
            `${arrCopy[mark + 1].startH}:${arrCopy[mark + 1].startM}`
          ) {
            // 修改的开始时间要 大于等于 之前的结束时间 或 修改的结束时间 小于等于 之后的 开始时间
            this.$message({
              type: 'warning',
              message: '时间段存在重复，请检查后重新设置',
            })
            return false
          }
        }
      }
      item.left = this.conversionpx('left', item)
      item.width = this.conversionpx('width', item)
      item.changeTimeShow = !item.changeTimeShow
      item.value = this.sonVal
      item.bg = this.adjustment(item.value)
      this.iShow = null
    },
    // 小弹框显示时触发
    showFun(item) {
      this.popoverStubData.push(JSON.parse(JSON.stringify(item)))
    },
    // 小弹框隐藏时触发
    hideFun(item) {
      if (this.iShow != null) {
        item.endH = this.popoverStubData[0].endH
        item.endM = this.popoverStubData[0].endM
        item.startH = this.popoverStubData[0].startH
        item.startM = this.popoverStubData[0].startM
      }
      this.popoverStubData.splice(0, 1)
    },
    // 剥离自定义指令的小时事件
    hhInput(val, code, key, item) {
      var reg = RegExp(/\D/)
      if (reg.test(item[val])) {
        item[val] = '00'
      } else if (item[val] >= 24) {
        item[val] = 24
        if (item[val] == 24) {
          item[val == 'startH' ? 'startM' : 'endM'] = '00'
        }
      }
    },
    // 剥离自定义指令的分钟事件
    mmInput(val, code, key, item) {
      var reg = RegExp(/\D/)
      // 数字验证
      if (reg.test(item[val]) || item['startH'] == 24 || item['endH'] == 24) {
        item[val] = '00'
      } else if (item[val] > 59) {
        item[val] = 59
      }
    },
    // 点击确定后验证时间数据是否需要添加 '0' 或者 '00' 或者不变
    timeVerification(time) {
      let timeData = time.toString()
      if (timeData.length == 0) {
        return '00'
      } else if (timeData.length == 1) {
        return `0${timeData}`
      } else if (timeData.length == 2) {
        return timeData
      }
    },
    // 确定
    submit() {
      if (!this.searchForm.baseId) {
        this.$message({
          type: 'warning',
          message: '请选择基地',
        })
        return false
      }
      // this.$emit('returnSubmit')
      // console.log(this.domObj,'---===storagePlanId=',this.id,"查看data内的数据==>>", JSON.stringify(this.weekList));
      this.addStorageCycle()
    },
    submitRW() {
      if (!this.searchForm.baseId) {
        this.$message({
          type: 'warning',
          message: '请选择基地',
        })
        return false
      }
      sendBaseBoxCmd({ id: this.searchForm.baseId }).then((res) => {
        if (res.code == 200) {
          this.$message({
            type: 'success',
            message: '任务下发成功',
          })
        } else {
          this.$message({
            type: 'warning',
            message: res.msg,
          })
        }
      })
    },
    getCompanyInfoTree() {
      if (!this.searchForm.userType) {
        return
      }

      if (this.searchForm.userType == 0) {
        // 超级管理员，公司只有一个总公司
        this.companyArray = [
          {
            id: 0,
            name: '总公司',
            parentId: 0,
          },
        ]
      } else {
        getCompanyInfoTree({ id: 0 }).then((res) => {
          if (res.code == 200) {
            this.companyArray = res.data
            if (res.data.length > 0) {
              this.searchForm.companyId = res.data[0].id
              this.getSysCompanyBases()
            }
          }
        })
      }
    },
    changeTreeItem(val) {
      if (val) {
        this.searchForm.companyId = val[val.length - 1]
      } else {
        this.searchForm.companyId = ''
      }

      this.searchForm.baseId = ''
      this.baseArray = []

      // 获取角色列表
      this.getSysCompanyBases()
    },
    getSysCompanyBases() {
      if (
        this.searchForm.companyId === '' ||
        this.searchForm.companyId == null
      ) {
        return
      }

      getSysCompanyBases({ id: this.searchForm.companyId }).then((res) => {
        if (res.code == 200) {
          this.baseArray = res.data
          if (res.data.length > 0) {
            this.searchForm.baseId = res.data[0].id
            this.listStorageCycle()
          }
        }
      })
    },
    listStorageCycle() {
      getObjBoxTaskList(this.searchForm).then((res) => {
        if (res.code === 200) {
          if (this.searchForm.fishpondCode) {
            this.showsave = false
          } else {
            this.showsave = true
          }
          // 此处如果接口正常并且有数据才能进行操作
          let weekList = []
          res.data.forEach((i, index) => {
            let week = {
              id: i.id,
              dischargeWaterGroupId: i.dischargeWaterGroupId,
              title: i.fishpondCode,
              code: index,
              copyShow: false,
              domArr: [],
              disabled: false,
            }
            let domArr = []
            i.taskList.forEach((j) => {
              let obj = {
                baseId: j.baseId,
                companyId: j.companyId,
                dischargeWaterGroupId: j.dischargeWaterGroupId,
                fishpondId: j.fishpondId,
                taskName: j.taskName,
                type: j.type,
                bg: this.adjustment(j.type), //背景色（与背景值关联，对应着下拉框的值
                value: j.type, //背景值（与背景色关联，对应着下拉框的值
                startH: j.startTime.split(':')[0], //开始时间（时
                startM: j.startTime.split(':')[1], //开始时间（分
                endH: j.endTime.split(':')[0], //结束时间（时
                endM: j.endTime.split(':')[1], //结束时间（分
                changeTimeShow: false, //控制时间显示与时间调整
              }
              obj.left = this.conversionpx('left', obj)
              obj.width = this.conversionpx('width', obj)
              domArr.push(obj)
            })
            week.domArr = domArr
            console.log(week.domArr)
            weekList.push(week)
          })
          this.weekList = weekList
          console.log(this.weekList)
        } else if (res.code != 200) {
          this.$message({
            type: 'warning',
            message: res.msg,
          })
        }
        this.btnLoading = false
      })
    },
    // 新增或修改
    addStorageCycle() {
      this.btnLoading = true
      // 数据处理
      let params = []
      this.weekList.forEach((i) => {
        i.domArr.forEach((j) => {
          if (j) {
            j.baseId = this.searchForm.baseId
            j.companyId = this.searchForm.companyId
            j.dischargeWaterGroupId = i.dischargeWaterGroupId
            j.fishpondId = i.id
            j.type = j.value
            j.startTime = `${j.startH}:${j.startM}`
            j.endTime = `${j.endH}:${j.endM}`
            j.durationTime =
              (parseInt(j.endTime.replace(':', '')) -
                parseInt(j.startTime.replace(':', ''))) *
              60
            // let obj = {
            //     startTime: `${j.startH}:${j.startM}`, //存储开始时间 HH:MM
            //     endTime: `${j.endH}:${j.endM}`, //存储结束时间 HH:MM
            //     storagePlanId: this.id, //存储计划id
            //     type: j.value, //存储计划周期类型（1=定时 2=移动侦测 3=报警 4=动测或报警 5=动测和报警 6=事件）
            //     week: i.code + 1, //星期(1~7)
            //     width: j.width, //宽
            //     left: j.left, //left
            // };
            params.push(j)
          }
        })
      })
      saveConfigFishpondTasks({
        baseId: this.searchForm.baseId,
        taskList: params,
      }).then((res) => {
        // console.log('新增或者修改返回==>',res)
        if (res.code == 200) {
          this.$message({
            type: 'success',
            message: res.msg,
          })
        } else {
          this.$message({
            type: 'warning',
            message: res.msg,
          })
        }
        this.btnLoading = false
      })
    },
    // 当要传的数据是[]时则调用（删除所有）
    delStorageCycle() {
      delStorageCycle(this.deleteId).then((res) => {
        if (res.code == 200) {
          this.$modal.msgSuccess(this.$t('public.successfulTexts'))
          this.$emit('returnSubmit')
        } else {
          this.$modal.msgError(this.$t('public.failedTexts'))
        }
        this.btnLoading = false
      })
    },
  },
}
</script>
<style lang="less" scoped>
/*滚动条整体样式*/
::-webkit-scrollbar {
  width: 4px;
  height: 10px;
}

/*滚动条里面小方块*/
::-webkit-scrollbar-thumb {
  border-radius: 10px;
  background: #48a0f8;
}

/*滚动条里面轨道*/
::-webkit-scrollbar-track {
  border-radius: 10px;
  background: #ededed;
}

.plan-content {
  //   position: absolute;
  //   top: 0;
  //   bottom: 0;
  min-height: calc(100vh - 90px);
  width: 100%;
  background: #2a2d3c;

  .titleycboxout {
    width: 100%;
    display: flex;
    align-items: center;
    justify-content: center;
    margin-top: 30px;
  }

  .titleycbox {
    width: 100%;
    display: flex;
    align-items: center;
    justify-content: space-between;

    // margin-left: 30px;
    .yleft {
      color: white;
      font-size: 16px;
      display: flex;
      align-items: center;

      .circle {
        width: 5px;
        height: 5px;
        background: #48a0f8;
        border-radius: 50%;
        margin-right: 3px;
      }
    }
  }

  .search {
    width: 97px;
    height: 40px;
    line-height: 40px;
    font-size: 15px;
    font-weight: bold;
    padding-left: 49px;
    cursor: pointer;
    color: black;
    background-image: url('../../../assets/schedule/search.png');
    background-size: 97px 40px;
    background-position: center center;
    background-repeat: no-repeat;
    position: relative;

    .glass {
      position: absolute;
      top: 14px;
      left: 10px;
    }
  }

  .search:hover {
    color: #8b8b8b;
  }

  .nx-content {
    height: 100%;
  }

  .labelitem {
    display: flex;
    align-items: center;
    color: white;
    font-size: 16px;
    margin: 0 20px;
    cursor: pointer;

    .cricle {
      margin-right: 7px;
      width: 4.16rem;
      height: 1.66rem;
    }

    .green {
      background-image: url(../../../assets/schedule/yu.png);
      background-size: 100% 100%;
      background-position: center center;
      background-repeat: no-repeat;
    }

    .grey {
      background-image: url(../../../assets/schedule/wu.png);
      background-size: 100% 100%;
      background-position: center center;
      background-repeat: no-repeat;
    }

    .blue {
      background-image: url(../../../assets/schedule/shui.png);
      background-size: 100% 100%;
      background-position: center center;
      background-repeat: no-repeat;
    }

    .purple {
      background-image: url(../../../assets/schedule/yu2.png);
      background-size: 100% 100%;
      background-position: center center;
      background-repeat: no-repeat;
    }
  }

  .redborder {
    border: 1px solid red;
  }

  .title-box {
    margin-bottom: 20px;
  }

  .title {
    margin-left: 10px;
  }

  .df {
    display: flex;
  }

  .dfcontent {
    overflow: auto;
    // display: flex;
    // flex-direction: column;
    // align-items: center;
    // justify-content: center;
  }

  .week-box {
    display: flex;
    flex-direction: column;
  }

  .cycle-box {
    margin: 25px 0;
    width: 7280px;
    display: flex;
    align-items: center;
  }

  .week {
    color: white;
    margin: 37px 30px 3.5px 0px;
  }

  /* 此处总长是720，是一天1440分钟的一半 */
  .slide-list {
    width: 7200px;
    //   width: 2160px;
    color: white;
  }

  .slide-ruler {
    position: relative;
    left: -5px;
    width: 7210px;
    display: flex;
    justify-content: space-between;
  }

  .scale {
    text-align: center;
    width: 15px;
    font-size: 12px;
  }

  .slide-box {
    width: 100%;
    height: 20px;
    background: #fff;
    display: flex;
    position: relative;
  }

  .item {
    height: 100%;
    position: absolute;
    background-size: 100% 100%;
    display: flex;
    align-items: center;
    justify-content: center;
  }

  .i-class {
    width: 6px;
    height: 20px;
    position: absolute;
    display: inline-block;
    background-position: -5px;
    z-index: 1;
  }

  .i-left-class {
    left: -3px;
  }

  .i-right-class {
    right: -3px;
  }

  .i-class:hover {
    cursor: w-resize;
  }

  .timeHover {
    width: 100%;
    height: 100%;
    display: inline-block;
  }

  .copy-class {
    justify-content: space-between;
    border-bottom: 1px solid #eeeeee;
  }

  .checkbox-class {
    margin: 5px 10px;
  }

  .color-class {
    align-items: center;
    margin-bottom: 10px;
  }

  .color-bg {
    width: 20px;
    height: 20px;
    margin-right: 10px;
  }

  .rbtn {
    display: flex;
    align-items: center;
    justify-content: center;
    margin-top: 10px;

    .removebtn {
      cursor: pointer;
      width: 111px;
      height: 35px;
      line-height: 35px;
      display: flex;
      align-items: center;
      justify-content: center;
      background: #f2f6fc;
      border-radius: 26px;
      border: 1px solid #48a0f8;
      color: #48a0f8;
      font-size: 14px;

      img {
        width: 17px;
        height: 17px;
      }
    }

    .btnsave {
      cursor: pointer;
      width: 111px;
      height: 35px;
      line-height: 35px;
      text-align: center;
      background: #48a0f8;
      border-radius: 26px;
      color: #ffffff;
      font-size: 14px;
      margin-left: 33px;
    }
  }
}

.w40 {
  width: 40px !important;
}
</style>
<style>
.el-tooltip__popper {
  padding: 5px 5px;
}

.el-tooltip__popper {
  background: #1cd8cf;
  color: #fff;
}

.el-tooltip__popper.is-dark {
  background: #a135e9;
}

.el-tooltip__popper .popper__arrow:after {
  border-top-color: #1cd8cf;
}

.el-tooltip__popper.is-dark .popper__arrow:after {
  border-top-color: #a135e9;
}
</style>
